/*
 * @Author: wwssaabb
 * @Date: 2021-11-11 09:33:36
 * @LastEditTime: 2021-12-18 09:48:27
 * @FilePath: \handwritten-code\promise\all.js
 */

//实现promise.all
//接收一个数组，如果元素不是promise则设为完成，
//当全部的promise完成时返回结果数组
//当有一个错误时，改变状态为rejected，返回这个错误


const myAll = function (arr) {
  let res = [],
    count = 0
  return new Promise((resolve, reject) => {
    if (arr.length === 0) return resolve(arr)
    arr.forEach((p, index) => {
      Promise.resolve(p).then(val => {
        res[index] = val
        if (++count === arr.length) resolve(res)
      }, reject)
    })
  })
}

//测试

const p1 = new Promise((resolve, reject) => setTimeout(() => {
  resolve('p1')
  // reject('p1')
}, 2000))
const p2 = new Promise(resolve => setTimeout(() => {
  resolve('p2')
}, 1000))
const p3 = new Promise(resolve => setTimeout(() => {
  resolve('p3')
}, 500))
const p4 = new Promise(resolve => setTimeout(() => {
  resolve('p4')
}, 4000))
const p5 = new Promise(resolve => setTimeout(() => {
  resolve('p5')
}, 5000))

let p = [p1, p2, p3, p4, p5, 1, 2, false, null];
// let p = [];
(async function () {
  myAll(p).then(res => console.log('success:' + res)).catch(err => console.log('error:' + err))
  Promise.all(p).then(res => console.log('success:' + res)).catch(err => console.log('error:' + err))
  // Promise.all([]).then(res => console.log(res))
})()